<?php
class Tv_Arte_Header_Helpers
{

	const XML_PATH = '../assets/xml/';

	/**
	 * Recherche dans les xml
	 *
	 * @param   String query
	 * @return  String HTML
	 */
	public static function search()
	{
	    $html = "";
	    $results = Array();
	    $tokens = explode(' ', $_POST['query']);
	    foreach ($it = new DirectoryIterator(self::XML_PATH) as $key => $value) {
	        if ('xml' == Tv_Arte_Utils_Str::getFileExtension($it->getFileName())) {
	            $match = false;
				$contents = file_get_contents($path = self::XML_PATH . $it->getFileName());
				foreach ($tokens as $word) {
				    if (false !== strpos($contents, $word)) {
				        $match = true;
				    }
				}
				if ($match) {
					$xml = simplexml_load_file($path);
					$result = $xml->xpath('/root/titleExtra_fr');
					$label = (is_array($result) && count($result) == 1) ? (string)$result[0] : $path;
				    $results[$path] = $label;
				}
	        }
	    }
	    if (count($results) > 0) {
	        $html =
			  "<div style=\"float:right;\">"
			. "\t<a style=\"margin-top:-5px; margin-right:1px;\" onclick=\"\$('#search-result').hide(); $('#search').val(''); return false;\" href=\"/\" class=\"cmn-button\">X</a>"
			. "</div>\n"
			. "<ul>\n";
		    foreach ($results as $path => $label) {
                $html .=
			  "\t<li>"
			. "<strong style=\"font-weight:bold; display:inline-block; max-width:100px; min-width:100px;\">" . $label . "</strong>"
			. "&nbsp;<a class=\"cmn-button\" onclick=\"Tv_Arte_Generator.showXml(this.href); return false;\" href=\"" . $path . "\">XML</a>"
			. "&nbsp;<a class=\"cmn-button\" onclick=\"Tv_Arte_Generator.showEmbedCode('" . basename($path, '.xml') . "'); return false;\" href=\"" . $path . "\">CODE</a>"
			. "&nbsp;<a class=\"cmn-button\" onclick=\"Tv_Arte_Generator.showPreview(this.href); return false;\" href=\"" . Tv_Arte_Header_Env::get('root_http') . "/render/preview.php?embedcode=" . urlencode(self::getEmbedCode(basename($path, '.xml'))) . "\">PREVIEW</a>"
			. "</li>\n";
		    }
		    $html .= "</ul>\n";
	    }
		return $html;
	}

	/**
	 * @param   String path
	 * @return	String json (xml, path)
	 */
	public static function getXml()
	{
	    return json_encode(Array(
			'xml' => file_get_contents($_POST['path']),
			'path' => $_POST['path']
		));
	}

	/**
	 * Renvoie en json un tableau de la forme
	 *
	 * @param   Array 'siteType' => String
	 * {
	 *  imageUrl:'http://...'
	 * 	urls:{
	 *		fr:'url_fr'
     *		de:'url_de'
     *		en:'url_en'
     * 	}
     * }
     * @return  String
	 */
	public static function getUrls()
	{
	    $header = Tv_Arte_Header::getInstance($_POST);
	    $config = $header->getCurrent();
	    $langs = $header->getLanguages();
     	return json_encode(Array(
     	    'imageUrl' => $config['logo'],
     	    'urls' => Array(
     	    	'fr' => (isset($langs['fr'])) ? Tv_Arte_Header_Translate::get($config['_metas']['url_key'], 'fr') : '',
     	    	'de' => (isset($langs['de'])) ? Tv_Arte_Header_Translate::get($config['_metas']['url_key'], 'de') : '',
     	    	'en' => (isset($langs['en'])) ? Tv_Arte_Header_Translate::get($config['_metas']['url_key'], 'en') : ''
			),
			'titles' => Array(
			    'fr' => (isset($langs['fr'])) ? Tv_Arte_Header_Translate::get($config['_metas']['title_key'], 'fr') : '',
     	    	'de' => (isset($langs['de'])) ? Tv_Arte_Header_Translate::get($config['_metas']['title_key'], 'de') : '',
     	    	'en' => (isset($langs['en'])) ? Tv_Arte_Header_Translate::get($config['_metas']['title_key'], 'en') : ''
			)
     	));
	}

	/**
	 *
	 * @param   Array json => String
	 * Décodé, cela donne
	 *
		stdClass Object
		(
		    [imageData] =>
		    [siteType] => arte-radio
		    [url_fr] => http://www.arteradio.com/
		    [url_de] => http://www.arteradio.com/radio-allemand.html
		    [url_en] => http://www.arteradio.com/
		    [urlExtra_fr] => http://www.arteradio.com/
		    [urlExtra_de] => http://www.arteradio.com/radio-allemand.html
		    [urlExtra_en] => http://www.arteradio.com/
		    [showLogin] => 1
		    [cbSocial] => 1
		)
	 * @return  String
	 */
	public static function save()
	{
	    $UID = uniqid();
	    $formData = json_decode($_POST['json']);
	    $logo = '';
	    if (0 !== strpos($formData->imageUrl, 'data:image/')) {
	        // l'image n'est pas encodee en base64
	        //$bytes = file_get_contents($formData->imageUrl);
            //$extension = Tv_Arte_Utils_Str::getFileExtension($formData->imageUrl);
            //$formData->imageUrl = 'data:image/' . $extension . '; base64,' . base64_encode($bytes);
            $logo = $formData->imageUrl;
	    } else {
		    preg_match('/image\/([a-zA-Z]+)/', $formData->imageUrl, $matches);
		    $extension = strtolower($matches[1]);
		    if ($extension == 'jpeg') {
	        	$extension = 'jpg';
		    }
		    $contentsSplit = explode(',', $formData->imageUrl);
		   	$encoded = $contentsSplit[count($contentsSplit) - 1];
		   	$decoded = "";
		   	for ($i = 0; $i < ceil(strlen($encoded) / 256); $i++) {
		      	$decoded = $decoded . base64_decode(substr($encoded, $i * 256, 256));
		   	}
		   	$contents = $decoded; // output
			$tmpPath = 'tmp_' . $UID . '.' . $extension;
			$name = $UID . '.' . $extension;
			if (false !== ($handle = fopen($tmpPath, 'w'))) {
				if (false !== fwrite($handle, $contents)) {
					fclose($handle);
					$img = new Tv_Arte_Utils_Image($tmpPath);
					$img->resizeImage($formData->imageW, $formData->imageH, 'exact');
					$img->saveImage(self::XML_PATH . $name);
					unlink($tmpPath);
					$logo = Tv_Arte_Header_Env::get('root_http') . '/assets/xml/' . $name;
				}
			}
	    }
	    $xml = new SimpleXMLElement('<root></root>');
     	$xml->addAttribute('uid', 			$UID);
	    $xml->addAttribute('timestamp', 	time());
        $xml->addChild('logo', 				$logo);
	    $xml->addChild('siteType', 			$formData->siteType);
		$xml->addChild('url_fr', 			$formData->url_fr);
		$xml->addChild('url_de', 			$formData->url_de);
		$xml->addChild('url_en', 			$formData->url_en);
		$xml->addChild('titleExtra_fr', 	$formData->titleExtra_fr);
        $xml->addChild('titleExtra_de', 	$formData->titleExtra_de);
        $xml->addChild('titleExtra_en', 	$formData->titleExtra_en);
        $xml->addChild('urlExtra_fr', 		$formData->urlExtra_fr);
        $xml->addChild('urlExtra_de', 		$formData->urlExtra_de);
        $xml->addChild('urlExtra_en', 		$formData->urlExtra_en);
        $xml->addChild('showLogin', 		(isset($formData->showLogin) ? 'true' : 'false'));
	    $xml->addChild('showSocial', 		(isset($formData->showSocial) ? 'true' : 'false'));
	    $xml->addChild('showLang', 			(isset($formData->showLang) ? 'true' : 'false'));
	    // Passage dans domdocument par maniaquerie, pour donner une belle indentation
	    $dom = new DOMDocument('1.0');
		$dom->preserveWhiteSpace = false;
		$dom->formatOutput = true;
		$dom->loadXML($xml->asXML());
		$result = (false !== $dom->save(self::XML_PATH . $UID . '.xml'));
		$code = self::getEmbedCode($UID);
		self::generate();
	    return json_encode(Array(
			'result' => $result,
			'UID' => $UID,
			'code' => $code
		));
	}

	/**
	 * Renvoie le code embed
	 *
	 * @param   String
	 * @return  String
	 */
	public static function getEmbedCode($UID=null)
	{
		$UID = (isset($_POST['UID'])) ? $_POST['UID'] : $UID;
	    return '<script type="text/javascript" src="' . Tv_Arte_Header_Env::get('root_http') . '/assets/js/Tv_Arte_IFrame.js?id=' . $UID . '&amp;lang="></script>';
	}

	/**
	 * Renvoie getCacheableEmbedCode
	 *
	 * @param   String
	 * @return  String
	 */
	public function getCacheableEmbedCode($UID=null)
	{
		$UID = (isset($_POST['UID'])) ? $_POST['UID'] : $UID;
	   	 return (APPLICATION_ENV == 'development')
			? '<script type="text/javascript" src="' . Tv_Arte_Header_Env::get('root_http') . '/assets/js/Tv_Arte_CacheableIFrame.js?id=' . $UID . '&amp;lang="></script>'
			: '<script type="text/javascript" src="http://www.arte.tv/Tv_Arte_CacheableIFrame_' . $UID . '_.js"></script>';
	}

	public function getCachedFiles($UID=null)
	{
	    $UID = (isset($_POST['UID'])) ? $_POST['UID'] : $UID;
	    $html = '<ul>';
	    foreach ($it = new DirectoryIterator('../static') as $key => $value) {
	        if (0 === strpos($it->getFileName(), $UID) || 0 === strpos($it->getFileName(), 'jsonp_' . $UID)) {
	            $file = Tv_Arte_Header_Env::get('root_http') . '/static/' . $it->getFileName();
                $html .= '<li><a style="font-size:10px;" onclick="window.open(this.href); return false;" href="' . $file . '">' . $file . '</a></li>';
	        }
	    }
	    $html .= '</ul>';
	    return $html;
	}

	public static function getJsonpCode($UID=null)
	{
	    $UID = (isset($_POST['UID'])) ? $_POST['UID'] : $UID;
	    return '<script type="text/javascript" src="' . Tv_Arte_Header_Env::get('root_http') . '/assets/js/Tv_Arte_HeaderInclude.js?id=' . $UID . '&amp;lang=fr"></script>';
	}

	public static function getCode($UID=null)
	{
	    $UID = (isset($_POST['UID'])) ? $_POST['UID'] : $UID;
	    $html = '<h2>Code à insérer juste avant la balise &lt;/body&gt;</h2>'
	        . '<br /><br /><h3>Code iframe :</h3>'
	        . '<input style="width:500px; font-size:10px;" class="textfield" type="text" value="' . htmlentities(self::getCacheableEmbedCode($UID)) . '" />'
	        . '<br /><br /><h3>Code jsonp :</h3>'
         	. '<input style="width:500px; font-size:10px;" class="textfield" type="text" value="' . htmlentities(self::getJsonpCode($UID)) . '" />'
         	. ((APPLICATION_ENV != 'development')
				? '<br /><br /><input style="width:500px; font-size:10px;" class="textfield" type="text" value="' . htmlentities('<script type="text/javascript" src="http://www.arte.tv/Tv_Arte_HeaderIncludeJsonp_' . $UID . '_fr.js"></script>') . '" />'
				: ''
			)
			. '<br /><br /><h3>Fichiers statiques :</h3>'
			. self::getCachedFiles($UID)
		;
		return $html;
	}

	/**
	 * Generation des fichiers statiques HMTL
	 *
	 * @param   id, soit il est vide et on genere tout, soit une id et on genere
	 *
	 */
	public static function generate()
	{
        foreach ($it = new DirectoryIterator(self::XML_PATH) as $key => $value) {
            $filterExtension = ('xml' == Tv_Arte_Utils_Str::getFileExtension($it->getFileName()));
            $filterId = ((!isset($_POST['id'])) || (isset($_POST['id']) && false !== strpos($it->getFileName(), $_POST['id'])));
	    	if ($filterExtension && $filterId) {
			    $id = basename($it->getFileName(), '.xml');
				$xmlPath = self::XML_PATH . $it->getFileName();
				$config = simplexml_load_file($xmlPath);
                $config = get_object_vars($config);
				$header = Tv_Arte_Header::getInstance($config);
				foreach ($header->getLanguages() as $lang => $v) {
				    $config['lang'] = $lang;
				    $header = Tv_Arte_Header::createInstance($config);
				    $file = '../static/' . $id . '_' . $lang . '.html';
	    	    	if (file_exists($file)) { unlink($file); }
				    $view = new Tv_Arte_View();
					$view->assign('config', 	$header->getConfig())
						->assign('showLang', 	$header->getShowLang())
						->assign('showLogin', 	$header->getShowLogin())
						->assign('showSocial', 	$header->getShowSocial())
						->assign('current', 	$header->getCurrent())
						->assign('langs', 		$header->getLanguages())
						->assign('xml', 		$config)
						->assign('lang', 		$lang);
					$html = $view->render('../tpl/render-index.php');
					file_put_contents($file, Tv_Arte_Utils_HTMLMin::minify($html));

					$file = '../static/jsonp_' . $id . '_' . $lang . '.html';
					if (file_exists($file)) { unlink($file); }
					$html = $view->render('../tpl/render-jsonp.php');
					file_put_contents($file, Tv_Arte_Utils_HTMLMin::minify($html));
				}
	    	}
		}
	}

	// ------------------------------------------------------------------------- //
	// ----- DEPRECATED --------------------------------------------------------
	// ------------------------------------------------------------------------- //

	/**
	 * Service http pour afficher les langues dispo en fonction du type de site
	 * @return  String
	 */
	public static function updateLangs()
	{
		$header = Tv_Arte_Header::getInstance($_GET);
		$html = "";
	    foreach ($header->getLanguages() as $k => $v) {
	        $html .= "<option value=\"" . $k . "\">" . $v['label'] . "</option>\n";
	    }
		return $html;
	}

	/**
	 * Service http de generation du javascript
	 * @return  String
	 */
	public static function writeJs()
	{
		$header = new Tv_Arte_View();
		$tpl = sprintf('../tpl/%s', 'generator-writejs.php');
	    return isset($_GET['minify']) ? Tv_Arte_Utils_JSMin::minify($header->render($tpl)) : $header->render($tpl);
	}

	/**
	 * Image saving
	 * @return String json
	 */
	public static function saveImage()
	{
		$response = Array('success' => false);
		if ($_POST['imageData']) {
			$UID = uniqid();
		   	$contentsSplit = explode(',', $_POST['imageData']);
		   	$encoded = $contentsSplit[count($contentsSplit)-1];
		   	$decoded = "";
		   	for ($i = 0; $i < ceil(strlen($encoded) / 256); $i++) {
		      	$decoded = $decoded . base64_decode(substr($encoded, $i * 256, 256));
		   	}
		   	$contents = $decoded; // output
		   	$extension = Tv_Arte_Utils_Str::getFileExtension($_POST['name']);
			$tmpPath = 'tmp_' . $UID . '.' . $extension;
			$name = $UID . '.' . $extension;
			if (false !== ($handle = fopen($tmpPath, 'w'))) {
				if (false !== fwrite($handle, $contents)) {
					fclose($handle);
					$img = new Tv_Arte_Utils_Image($tmpPath);
					$img->resizeImage($_POST['w'], $_POST['h'], 'exact');
					$img->saveImage('./configs/' . $name);
					$response = Array('success' => true, 'uid' => $UID, 'name' => $name);
					unlink($tmpPath);
				}
			}
		}
		return json_encode($response);
	}
}